import express, { Request, Response } from "express"
import { LoggedInRequest } from "../../types"
import { checkError } from "../../utils/token"
import { useCheckAndResponse } from "../../utils/common"
import { OrderContext } from "../../context/OrderContext"
import { AddOrderItemType, CreateOrderParamType, GetOrderListParamType } from "@Tea/model"
import { ShoppingCarCtx } from "../../context/ShoppingCarCtx"

const orderRouter = express.Router()

orderRouter.post("/createOrder", async (req: LoggedInRequest, res: Response) => {
  try {
    const params = req.body as CreateOrderParamType
    // 需要传入 shoppingcarId 的数组
    if (!params.shoppingIds?.length) {
      return res.send({
        code: 0,
        msg: "请求参数错误"
      })
    }

    // 判断购物车中是否有相应的商品
    const carList = await ShoppingCarCtx.getInstance().shoppingCarListByIds(params.shoppingIds, req.userInfo.userId)
    if (carList.length !== params.shoppingIds.length) {
      return res.send({
        code: 0,
        msg: "购物车中不存在商品"
      })
    }

    // 创建订单
    const { result: createOrderRes, orderNo } = await OrderContext.getInstance().createOrder(req.userInfo.userId, params.address)
    // 创建失败就返回
    if (createOrderRes[0].affectedRows !== 1) {
      return res.send({
        code: 0,
        msg: '订单创建失败'
      })
    }

    // 删除购物车中的，加入到订单中
    await ShoppingCarCtx.getInstance().cancelCommodity({ shoppingIds: carList.map(c => c.shoppingId) }, req.userInfo.userId)
    const transferPromise = []
    carList.forEach(car => {
      const addParams: AddOrderItemType = {
        teaId: car.teaId,
        orderNumber: car.orderNumber,
        orderId: orderNo
      }
      transferPromise.push(OrderContext.getInstance().addOrderItem(addParams))
    })

    await Promise.all(transferPromise)

    res.send({
      code: 1,
      data: {
        orderId: orderNo
      },
      msg: '订单创建成功'
    })
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

orderRouter.delete("/cancelOrder", async (req: LoggedInRequest, res: Response) => {
  try {
    const query = req.query as any as { orderId: string }
    const delOrderRes = await OrderContext.getInstance().cancelOrder(query.orderId)

    // 校验订单
    if (delOrderRes[0].affectedRows === 0) {
      return res.send({
        code: 0,
        msg: "订单不存在"
      })
    }

    await OrderContext.getInstance().cancelOrderItem(query.orderId)

    res.send({
      code: 1,
      msg: '删除成功'
    })

  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

orderRouter.put("/pay", async (req: LoggedInRequest, res: Response) => {
  try {
    const params = req.body as any as { orderId: string }
    const payOrderRes = await OrderContext.getInstance().pay(params.orderId)

    // 校验订单
    if (payOrderRes[0].affectedRows === 0) {
      return res.send({
        code: 0,
        msg: "订单不存在"
      })
    }

    res.send({
      code: 1,
      msg: '支付成功'
    })

  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

orderRouter.put("/confirm", async (req: LoggedInRequest, res: Response) => {
  try {
    const params = req.body as any as { orderId: string }
    const confirmOrderRes = await OrderContext.getInstance().confirm(params.orderId)

    // 校验订单
    if (confirmOrderRes[0].affectedRows === 0) {
      return res.send({
        code: 0,
        msg: "订单不存在"
      })
    }

    res.send({
      code: 1,
      msg: '确认收货成功'
    })

  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

orderRouter.post("/orderList", async (req: LoggedInRequest, res: Response) => {
  try {
    const params = req.body as GetOrderListParamType
    const data = await OrderContext.getInstance().orderList(params, req.userInfo.userId)

    res.send({
      code: 1,
      msg: '查询成功',
      data
    })

  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

export default orderRouter